package pri.hillchen.std.concurrent.chapter5;

import java.util.Map;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 16:07 2018/2/8 0008.
 */
public class CyclicBarrierDemo {
    public static void main(String[] args){
        final ConcurrentHashMap<String,Long> concurrentHashMap = new ConcurrentHashMap<>();
        final AtomicLong resutl = new AtomicLong(0);
        final AtomicInteger step = new AtomicInteger(1);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5,new Runnable() {
            @Override
            public void run() {
                System.out.println(String.format("开始计算第%s的汇总结果。",step));
                for(Map.Entry<String,Long> entry : concurrentHashMap.entrySet()){
                    resutl.getAndAdd(entry.getValue());
                }
                System.out.println(String.format("第%s的汇总结果为:%s",step,resutl));
                step.getAndAdd(1);
            }
        });
        for(int i=0;i<5;i++){
            final String threadKey =  i+"";
            concurrentHashMap.put(threadKey,(long)i+1);
            new Thread(){
                @Override
                public void run() {
                    while (step.get() < 41){
                        Long  threadValue = concurrentHashMap.get(threadKey);
                        concurrentHashMap.put(threadKey,threadValue + threadValue);
                        try {
                            cyclicBarrier.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    }

}
